﻿namespace WLFramework.Reflection.Metadata
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    using WLFramework.Reflection;

    /// <summary>
    /// 实体类元数据， 类型、构造函数、属性设置委托、验证特性标记等。
    /// </summary>
    public class ModelMetadata
    {
        public Type Type { get; private set; }
        public TargetCreater Creator { get; private set; }

        public object Model { get; set; }

        public List<ModelMemberInfo> Members { get; private set; }
        public IModelMetadataProvider Provider { get; private set; }

        public ModelMetadata(IModelMetadataProvider provider, Type type)
        {
            Shield.AssertNotNull(ref type, "type");
            Shield.AssertNotNull(ref provider, "provider");

            this.Provider = provider;
            this.Type = type;

            this.Initialize();
        }

        private void Initialize()
        {
            this.Creator = this.Type.CreateConstructor();
            this.Model = this.Creator.Ctor();
            this.Members = this.Provider.GetMembers(this.Type).ToList();
        }

        public ModelMemberInfo GetMember(string name)
        {
            Shield.AssertNotNullOrEmpty(ref name, "property");
            var prop = this.Members.Where(k => k.MemberName == name).FirstOrDefault();
            return prop;
        }

        public object GetMemberValue(string name)
        {
            var prop = this.GetMember(name);
            Shield.AssertNotNull(ref prop, "prop");
            return prop.Getter.Getter(this.Model);
        }

        public string GetMemberDisplayName(string name)
        {
            var prop = this.GetMember(name);
            Shield.AssertNotNull(ref prop, "prop");
            return prop.Display == null ? name : prop.Display.Display;
        }
    }
}
